package com.aiYouPms.common.service.impl;

import com.aiYouPms.common.dao.AdminUserDao;
import com.aiYouPms.common.dao.AdminUserRoleDao;
import com.aiYouPms.common.model.AdminUser;
import com.aiYouPms.common.model.Role;
import com.aiYouPms.common.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class AdminUserServiceImpl implements AdminUserService {

    private final AdminUserDao adminUserDao;
    private final AdminUserRoleDao adminUserRoleDao;

    @Autowired
    public AdminUserServiceImpl(AdminUserDao adminUserDao, AdminUserRoleDao adminUserRoleDao) {
        this.adminUserDao = adminUserDao;
        this.adminUserRoleDao = adminUserRoleDao;
    }

    @Override
    public List<AdminUser> findAll(AdminUser adminUser) {
        List<AdminUser> users = adminUserDao.findAll(adminUser);
        // 为每个用户设置角色ID列表和角色列表
        for (AdminUser user : users) {
            List<Integer> roleIds = adminUserDao.findRoleIdsByUserId(user.getId());
            user.setRoleIds(roleIds);
            // 设置角色列表
            if (roleIds != null && !roleIds.isEmpty()) {
                List<Role> roles = adminUserDao.findRolesByRoleIds(roleIds);
                user.setRoles(roles);
            }
        }
        return users;
    }

    @Override
    public AdminUser findById(Integer id) {
        AdminUser user = adminUserDao.findById(id);
        return getAdminUser(user);
    }

    private AdminUser getAdminUser(AdminUser user) {
        if (user != null) {
            List<Integer> roleIds = adminUserDao.findRoleIdsByUserId(user.getId());
            user.setRoleIds(roleIds);

            // 设置角色列表
            if (roleIds != null && !roleIds.isEmpty()) {
                List<Role> roles = adminUserDao.findRolesByRoleIds(roleIds);
                user.setRoles(roles);
            }
        }
        return user;
    }

    @Override
    public AdminUser findByUsername(String username) {
        AdminUser user = adminUserDao.findByUsername(username);
        return getAdminUser(user);
    }

    @Override
    @Transactional
    public AdminUser create(AdminUser adminUser) {
        long currentTime = System.currentTimeMillis();
        adminUser.setCreatedAt(currentTime);
        adminUser.setUpdatedAt(currentTime);
        adminUser.encodePassword(adminUser.getPassword());
        adminUserDao.insert(adminUser);
        
        // 处理角色关联
        handleUserRoles(adminUser.getId(), adminUser.getRoleIds());
        
        return adminUser;
    }

    @Override
    @Transactional
    public AdminUser update(Integer id, AdminUser adminUser) {
        AdminUser existingUser = adminUserDao.findById(id);
        if (existingUser == null) {
            throw new RuntimeException("管理员用户不存在");
        }
        adminUser.setId(id);
        adminUser.setUpdatedAt(System.currentTimeMillis());
        adminUserDao.update(adminUser);
        
        // 处理角色关联
        handleUserRoles(id, adminUser.getRoleIds());
        
        return adminUser;
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        AdminUser existingUser = adminUserDao.findById(id);
        if (existingUser == null) {
            throw new RuntimeException("管理员用户不存在");
        }

        // 先删除用户角色关联
        adminUserRoleDao.deleteUserRolesByUserId(id);
        // 再删除用户
        adminUserDao.deleteById(id);
    }

    @Override
    public List<AdminUser> searchByUsername(String username) {
        List<AdminUser> users = adminUserDao.searchByUsername(username);
        // 为每个用户设置角色ID列表和角色列表
        for (AdminUser user : users) {
            List<Integer> roleIds = adminUserDao.findRoleIdsByUserId(user.getId());
            user.setRoleIds(roleIds);
            
            // 设置角色列表
            // 设置角色列表
            if (roleIds != null && !roleIds.isEmpty()) {
                List<Role> roles = adminUserDao.findRolesByRoleIds(roleIds);
                user.setRoles(roles);
            }
        }
        return users;
    }

    @Override
    public AdminUser loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminUser adminUser = adminUserDao.findByUsername(username);
        if (adminUser == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        // 设置角色ID列表
        List<Integer> roleIds = adminUserDao.findRoleIdsByUserId(adminUser.getId());
        adminUser.setRoleIds(roleIds);
        // 设置角色列表
        if (roleIds != null && !roleIds.isEmpty()) {
            List<Role> roles = adminUserDao.findRolesByRoleIds(roleIds);
            adminUser.setRoles(roles);

        }
        return adminUser;
    }
    
    /**
     * 处理用户角色关联
     * @param userId 用户ID
     * @param roleIds 角色ID列表
     */
    private void handleUserRoles(Integer userId, List<Integer> roleIds) {
        // 先删除原有的角色关联
        adminUserRoleDao.deleteUserRolesByUserId(userId);
        
        // 添加新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Integer roleId : roleIds) {
                adminUserRoleDao.insertUserRole(userId, roleId);
            }
        }
    }
}